/*
 * MonitorConfigFrame.java
 *
 * Created on May 18, 2008, 7:18 PM
 */

package pl.edu.agh.ssm.monitor.gui;

import java.awt.Component;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.SwingUtilities;
import jpcap.NetworkInterface;
import org.jdesktop.application.Action;
import org.jdesktop.application.Task;
import pl.edu.agh.ssm.monitor.SessionMonitorApp;
import pl.edu.agh.ssm.monitor.SessionMonitorManager;
import pl.edu.agh.ssm.monitor.listeners.ListenerConfig;

/**
 *
 * @author  aneezka
 */
public class MonitorConfigFrame extends javax.swing.JFrame {
    
    private static final long serialVersionUID = 7434435193913962340L;
	
	/** Creates new form MonitorConfigFrame */
    public MonitorConfigFrame() {
        initComponents();
        networkInterfaceComboBox.setRenderer(new ListCellRenderer() {

            public Component getListCellRendererComponent(JList arg0, Object arg1, int arg2, boolean arg3, boolean arg4) {
                JLabel label = new JLabel();
                label.setText(arg1.toString());
                if (arg1 instanceof NetworkInterface) {
                    NetworkInterface ni = (NetworkInterface) arg1;
                    label.setText(ni.description + " " + ni.name + "(" + ni.datalink_name + " " + ni.datalink_description + ")" );
                }
                return label;
            }
            
        });
        SessionMonitorManager manager = SessionMonitorApp.getApplication().getManager();
        for (String listener : manager.getAvailableListeners()) {
            ListenerConfigPanel l = new ListenerConfigPanel(listener);
            listenerPanels.add(l);
            jPanel3.add(l);
        }
        for (NetworkInterface ni : manager.getNetworkInterfaces()) {
            networkInterfaceComboBox.addItem(ni);
        }
    }
    
    public NetworkInterface getNetworkInterface() {
        if (networkInterfaceComboBox.getSelectedItem() == null || networkInterfaceComboBox.getSelectedItem().equals(chooseString)) {
            return null;
        } else {
            return (NetworkInterface)networkInterfaceComboBox.getSelectedItem();
        }
    }
    
    public boolean isPromiscuous() {
        return promiscuousCheckBox.isSelected();
    }
    
    public static  void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                JFrame frame = new MonitorConfigFrame();
                frame.setVisible(true);
            }
            
        });
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        networkInterfaceComboBox = new javax.swing.JComboBox();
        promiscuousCheckBox = new javax.swing.JCheckBox();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jPanel3 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(pl.edu.agh.ssm.monitor.SessionMonitorApp.class).getContext().getResourceMap(MonitorConfigFrame.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel1.border.title"))); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        networkInterfaceComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--choose--" }));
        networkInterfaceComboBox.setName("networkInterfaceComboBox"); // NOI18N

        promiscuousCheckBox.setSelected(true);
        promiscuousCheckBox.setText(resourceMap.getString("promiscuousCheckBox.text")); // NOI18N
        promiscuousCheckBox.setName("promiscuousCheckBox"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(networkInterfaceComboBox, 0, 522, Short.MAX_VALUE)
                    .addComponent(promiscuousCheckBox))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(networkInterfaceComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(promiscuousCheckBox)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel2.border.title"))); // NOI18N
        jPanel2.setName("jPanel2"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jPanel3.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jPanel3.setName("jPanel3"); // NOI18N
        jPanel3.setLayout(new java.awt.GridLayout(0, 1));
        jScrollPane1.setViewportView(jPanel3);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 522, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE)
                .addContainerGap())
        );

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(pl.edu.agh.ssm.monitor.SessionMonitorApp.class).getContext().getActionMap(MonitorConfigFrame.class, this);
        jButton2.setAction(actionMap.get("start")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton1, jButton2});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    @Action
    public Task<?, ?> start() {
        try {
            validateInput();
            Task<?, ?> task = new SessionMonitorApp.StartAppTask(getNetworkInterface(), isPromiscuous(), getConfigs());
            this.dispose();
            return task;
        } catch (InternalValidationException ex) {
            return null;
        }
    }
    
    private void validateInput() throws InternalValidationException {
        if (networkInterfaceComboBox.getSelectedItem() == null || networkInterfaceComboBox.getSelectedItem().equals(chooseString)) {
            throw new InternalValidationException("You have to choose network interface");
        }
        int counter = 0;
        for (ListenerConfigPanel l : listenerPanels) {
            if (l.isSelected()) {
                counter++;
//                if (l.getLowerPort() == null || l.getLowerPort().trim().equals("")) {
//                    throw new InternalValidationException("You have to specify port for " + l.getName());
//                }
//                try {
//                    Integer.parseInt(l.getLowerPort());
//                } catch (NumberFormatException e) {
//                    
//                }
            }
        }
        if (counter == 0) {
            throw new InternalValidationException("At least one of the listeners should be selected");
        }
    }
    
    private List<ListenerConfig> getConfigs() {
        List<ListenerConfig> result = new LinkedList<ListenerConfig>();
        for (ListenerConfigPanel l : listenerPanels) {
            if (l.isSelected()) {
                ListenerConfig config = new ListenerConfig();
                config.setType(l.getName());
                int lowPort = l.getLowerPort();
                int highPort = l.getHigherPort();
                config.setLowPort(lowPort);
                config.setHighPort(highPort);
                config.setIpAddress(l.getIpAddress());
                result.add(config);
            }
        }
        return result;
    }
    
    private static class InternalValidationException extends Exception {

      	private static final long serialVersionUID = 4214840966596216209L;

		private InternalValidationException(String string) {
            super(string);
        }
        
    }
    
    private final String chooseString = "--choose--";
    private List<ListenerConfigPanel> listenerPanels = new LinkedList<ListenerConfigPanel>();
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JComboBox networkInterfaceComboBox;
    private javax.swing.JCheckBox promiscuousCheckBox;
    // End of variables declaration//GEN-END:variables
    
}
